package com.fzy;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.groovy.control.CompilerConfiguration;

public class MyGroovyConsoleServlet extends HttpServlet {

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String script = request.getParameter("_s");
		
		Binding binding = new Binding();
		CompilerConfiguration config = new CompilerConfiguration();
		GroovyShell shell = new GroovyShell(binding, config);
		
        PrintStream oldPrintStream = System.out;        //将原来的System.out交给printStream 对象保存  
        ByteArrayOutputStream consoleResult = new ByteArrayOutputStream();   
        System.setOut(new PrintStream(consoleResult));         //设置新的out
        Object scriptResult = null;
        Throwable error = null;
        try {
        	scriptResult = shell.run(script, "test", new LinkedList());
		} catch (Throwable t) {
			error = t;
		}
        System.setOut(oldPrintStream);   //恢复原来的System.out  
        
        request.setAttribute("console", consoleResult);
        request.setAttribute("error", error);
        request.setAttribute("result", scriptResult);
        
        response.setCharacterEncoding("UTF-8");
		request.getRequestDispatcher("/result.jsp").forward(request, response);
	}




}
